<template>
    <div class="container">
        <Navbar title="订单结算" left-text="返回" left-arrow @click-left="goBack">
        </Navbar>

        <div id="address">
            <van-cell class="cai" v-if="addrnull" center is-link
                :to="{ name: 'AddressBase', query: { action, nums, idArr } }">
                <template #icon>
                    <van-icon size="1.5rem" name="wap-home-o" style="margin-right: .8rem;" />
                </template>

                <template #title>
                    <div>
                        <span class="left" style="margin-right: .5rem;">
                            姓名:{{ this.address.name }}
                        </span>
                        <span class="left">
                            电话:{{ this.address.mobile }}
                        </span>
                    </div>
                </template>

                <template #label>
                    <div style="font-size: .9rem;">
                        {{ this.address.info }}
                    </div>
                </template>

                <template #right-icon>
                    <van-icon name="arrow" />
                </template>
            </van-cell>

            <van-cell class="cai" v-else center is-link :to="{ name: 'AddressBase', query: { action, nums, idArr } }">
                <template #icon>
                    <van-icon size="1.5rem" name="add-o" style="margin-right: .8rem;" />
                </template>

                <template #title>
                    <div style="font-size: .9rem;">
                        添加地址
                    </div>
                </template>

                <template #right-icon>
                    <van-icon name="arrow" />
                </template>
            </van-cell>
        </div>

        <br>

        <van-cell title="GunDam自营社区" is-link />
        <van-card v-for="item in shops" :key="item.id" class="mt" :num="item.nums" :tag="item.flag_text"
            :price="item.price" desc="描述信息" :title="item.name" :thumb="item.cover_cdn" />

        <br>
        <van-cell title="支付方式" is-link />
        <van-cell title="优惠券" is-link />
        <br>

        <van-cell title="快递公司" is-link :value="tips" @click="showExp = true" />
        <van-cell title="运费" is-link value="￥ 0.00" />
        <br>

        <van-cell-group inset style="margin: 0;">
            <van-field v-model="message" rows="2" autosize label="买家留言" type="textarea" maxlength="50"
                placeholder="请填写备注(选填)" show-word-limit />
        </van-cell-group>


        <van-submit-bar :price="this.total" button-text="确定创建" @submit="onSubmit" />


        <van-dialog v-model:show="showKeyboard" title="请输入支付密码" theme="round-button" show-cancel-button
            cancel-button-text="再想想" confirm-button-text="稍后支付" confirm="confirm">

            <van-password-input :value="pwd" info="密码为6位数字" :error-info="errorInfo" :focused="showKeyboard" :length="6"
                @focus="showKeyboard = true" />

        </van-dialog>

        <van-number-keyboard v-model="pwd" :show="showKeyboard" @blur="showKeyboard = false" />

        <van-popup v-model:show="showExp" round position="bottom">
            <van-picker title="快递公司" :columns="columns" @cancel="showExp = false" @confirm="onConfirm" />
        </van-popup>
    </div>
</template>

<script>
import Navbar from '../Navbar.vue';
export default {
    name: "Buy",
    data() {
        return {
            idArr: this.$route.query.idArr ? this.$route.query.idArr : 0,
            address: {},
            shops: [],
            addrnull: true,
            showKeyboard: false,
            show: false,
            userid: this.$cookies.get('ShopUser') ? this.$cookies.get('ShopUser').id : 0,
            message: '',
            pwd: '',
            errorInfo: '',
            action: '',
            nums: 0,
            tips: '请选择快递公司',
            columns: [],
            expList: [],
            expid: 0,
            showExp:false
        };
    },
    methods: {
        goBack() {
            this.$router.push('/cart/base/index');
        },
        async initAddress() {
            let res = await this.$api.initAddress({ userid: this.userid });

            if (res.code === 1) {
                this.address = {
                    id: res.data.id,
                    name: res.data.consignee,
                    mobile: res.data.mobile,
                }

                let info = "";

                if (res.data.provinces) {
                    info += `${res.data.provinces.name}-`;
                }

                if (res.data.citys) {
                    info += `${res.data.citys.name}-`;
                }

                if (res.data.districts) {
                    info += `${res.data.districts.name} `;
                }

                if (res.data.address) {
                    info += `${res.data.address}`;
                }
                this.addrnull = true;
                this.address.info = info;
            } else {
                this.addrnull = false;
                console.log(res.msg);
            }
        },
        async initShop() {
            let idArr = this.idArr
            // console.log(idArr);
            let temp = [];
            // console.log(Array.from(idArr));

            if (typeof (idArr) === 'string') {
                temp = [];
                temp.push(idArr);
                idArr = temp;
            }

            let data = {
                idArr,
                action: this.action
            }

            let res = await this.$api.initShop(data);
            if (res.code === 1) {
                this.shops = res.data

                if (this.nums > 0) this.shops[0].nums = this.nums
                // console.log(res);
            } else {
                console.log(res.msg);
            }
        },
        async confirm() {
            // console.log(111);
            let data = {
                total: this.total * 0.01,
                userid: this.userid,
                addrid: this.address.id,
                content: this.message,
                idArr: this.idArr,
                action: '',
                action2: this.$route.query.action,
                content: this.message,
                nums: this.nums,
                expid: this.expid,
                orderid: 0
            }

            let res = await this.$api.create(data);

            if (res.code === 1) {
                this.$toast.success({
                    duration: 1500,
                    message: res.msg,
                    onClose: () => {
                        this.$router.push({ path: res.url, query: { orderid: res.data } });
                    }
                })
            } else {
                this.$notify({
                    type: 'danger',
                    message: res.msg
                })
            }
        },
        onConfirm(item, index) {
            this.expid = this.expList[index].id;
            this.showExp = false;
            this.tips = item
        },
        onSubmit() {
            if (this.expid == 0) {
                this.$notify({
                    type: 'warning',
                    message: '请选择快递公司',
                    duration: 1000
                })
                return false
            }

            this.$toast.loading({
                duration: 1000,
                forbidClick: true,
                loadingType: 'spinner',
                message: '正在创建订单',
                onClose: () => {
                    this.show = true
                    this.showKeyboard = true
                }
            })

        },
        async initExpress() {
            let res = await this.$api.initExpress();
            console.log(res.data);
            if (res.code === 1) {

                if (res.data.length <= 0) {
                    this.$notify({
                        type: 'warning',
                        message: '暂无数据'
                    })
                    return false
                }

                this.expList = res.data;
                res.data.forEach(item => {
                    this.columns.push(item.name);
                });
            } else {
                this.$notify({
                    type: "warning",
                    message: "获取失败",
                    onClose: () => {
                        return false;
                    },
                });
            }
        },

    },
    computed: {
        total() {
            let total = 0;

            if (this.nums > 0) {
                this.shops.forEach(item => {
                    total += parseFloat(item.price * this.nums)
                });
            } else {
                this.shops.forEach(item => {
                    total += parseFloat(item.total)
                });
            }

            return total * 100;
        },
    },
    watch: {
        pwd(newVal, oldVal) {
            let data = {
                total: this.total * 0.01,
                userid: this.userid,
                addrid: this.address.id,
                content: this.message,
                idArr: this.idArr,
                action: 'cash',
                action2: this.$route.query.action,
                content: this.message,
                nums: this.nums,
                expid: this.expid,
                orderid: 0
            }

            if (newVal.length === 4) {

                if (newVal === '1234') {
                    this.$toast.loading({
                        message: '支付中...',
                        duration: 1500,
                        onClose: async () => {
                            this.show = false
                            this.showKeyboard = false
                            this.pwd = ''

                            let res = await this.$api.create(data);

                            console.log(res);
                            // return false
                            if (res.code === 1) {
                                this.$toast.success({
                                    duration: 1500,
                                    message: res.msg,
                                    onClose: () => {
                                        this.$router.push({ path: res.url, query: { orderid: res.data } });
                                    }
                                })
                            } else {
                                this.$notify({
                                    type: 'danger',
                                    message: res.msg,
                                    duration: 1500,
                                })
                            }
                        }
                    })
                } else {
                    this.$toast.fail({
                        message: '密码错误',
                        duration: 500,
                        onClose: () => {
                            this.show = false
                            this.showKeyboard = false
                            this.pwd = ''
                        }
                    })
                }
            }
        }
    },
    created() {
        this.initAddress();
        this.initExpress();
        this.nums = this.$route.query.nums ? this.$route.query.nums : 0;
        this.action = this.$route.query.action ? this.$route.query.action : 'user';
        this.initShop();
    },
    components: {
        Navbar
    }
}
</script>

<style scoped>
:deep(.van-submit-bar__text) {
    text-align: left;
}

:deep(.van-number-keyboard) {
    z-index: 9999;
}

:deep(.van-submit-bar) {
    z-index: 1;
}

.mt {
    margin-top: 0;
    background: #fff;
}

.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.block {
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    width: auto;
    min-width: 80%;
    border-radius: 10px;
    height: 120px;
    background-color: #fff;
}

/* :deep(.van-password-input__security li) {
    border: 1px solid #000;
} */

#address :deep(.van-cell:before) {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    height: 2px;
    background: repeating-linear-gradient(-45deg, var(--van-warning-color) 0, var(--van-warning-color) 20%, transparent 0, transparent 25%, var(--van-primary-color) 0, var(--van-primary-color) 45%, transparent 0, transparent 50%);
    background-size: 80px;
    content: "";
}
</style>